package kr.co.hk.coupon;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.co.hk.R;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListOfInfo extends ListActivity {
	private ArrayList<MyItem> aMyItem;
	private String url = "";
	private MyListAdapter MyAdapter;
	private int page = 1;
	private BufferedReader br;
	
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	private boolean isMaxPage = false;
	private boolean pageEx = false;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.coupon_list);

		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		aMyItem = new ArrayList<MyItem>();
		getListView().setScrollingCacheEnabled(false);

		MyAdapter = new MyListAdapter(this, R.layout.date_row, aMyItem);
		setListAdapter(MyAdapter);
		mainProcessing();

		Button btnBack = (Button) findViewById(R.id.btnCouponBack);
		Button btnNext = (Button) findViewById(R.id.btnCouponNext);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int backPage = page - 1;
				if (backPage < 1) {
					toast("첫 페이지 입니다.");
				} else {
					page = backPage;
					mainProcessing();
				}
			}
		});

		btnNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isMaxPage) {
					toast("더 이상 없습니다.");
				} else {
					page = page + 1;
					mainProcessing();
				}

			}
		});

	}

	private void getHtml(String addr) {
		try {
			URL url_ = new URL(addr);
			HttpURLConnection conn = (HttpURLConnection) url_.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					br = new BufferedReader(new InputStreamReader(conn
							.getInputStream(), "euc-kr"));

					aMyItem.clear();
					String con1 = "";
					String addre = "";
					String imgUrl = "";
					String cont2 = "";

					String msg = "";
					while ((msg = br.readLine()) != null) {
						String line = msg;
						if (line
								.contains("href=\"http://www.cocofun.co.kr/CouponList/ShopInfo.asp?nStoreNo=")
								&& line.toLowerCase().contains(".jpg")) {
							imgUrl = line.substring(line.indexOf("src=") + 5,
									line.toLowerCase().indexOf("jpg") + 3);

							addre = line.substring(
									line.indexOf("nStoreNo=") + 9, line
											.indexOf("\"><img"));

						}
						if (line
								.contains("href=\"http://www.cocofun.co.kr/CouponList/ShopInfo.asp?nStoreNo=")
								&& line.contains("<div class=\"tt01\">")) {
							con1 = line.substring(
									line.indexOf("nStoreNo=") + 16, line
											.indexOf("</a></div>"));
						}
						if (line
								.contains("href=\"http://www.cocofun.co.kr/CouponList/ShopInfo.asp?nStoreNo=")
								&& line.contains("<div class=\"tt02\">")) {
							cont2 = line.substring(
									line.indexOf("nStoreNo=") + 16, line
											.indexOf("</a></div>"));

							InputStream is = new URL(imgUrl).openStream();

							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 4;
							options.inScaled = false;
							Bitmap src = BitmapFactory.decodeStream(is, null,
									options);

							MyItem item = new MyItem(src, con1, cont2, addre);
							aMyItem.add(item);

						}

						if (line.contains("스카이베너 시작"))
							break;
					}
					br.close();
				}
				conn.disconnect();
			}
		} catch (Exception ex) {
			pageEx = true;
			ex.printStackTrace();

		}

		return;
	}

	private void excePro() {
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}

	private Handler chdHandler = new Handler();

	private void mainProcessing() {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		Thread childThread = new Thread(null, dobackgroundThreadProcessing,
				"Backgroud");
		childThread.start();
	}

	private Runnable dobackgroundThreadProcessing = new Runnable() {

		@Override
		public void run() {
			backgroudnThreadProcessing();
		}
	};

	private void backgroudnThreadProcessing() {

		String page_url = url + "&Page=" + page;
		getHtml(page_url);
		chdHandler.post(doUpdateGUI);
	}

	private Runnable doUpdateGUI = new Runnable() {

		@Override
		public void run() {
			updateGUI();
		}
	};

	private void updateGUI() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		progressDialog.dismiss();
		ListOfInfo.this.removeDialog(PROGRESS_DIALOG);

		if (pageEx) {
			excePro();
		} else {
			MyAdapter.notifyDataSetChanged();
			getListView().setSelectionFromTop(0, 1);
			if (aMyItem.equals(null) || aMyItem.size() == 0) {
				toast("더 이상 없습니다.");
				isMaxPage = true;
			}else if(aMyItem.size()< 20){
				isMaxPage = true;
			} else {
				isMaxPage = false;
			}
		}

	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

	public void onListItemClick(ListView list, View view, int position, long id) {
		String url = "http://www.cocofun.co.kr/CouponList/ShopInfo.asp?nStoreNo="
				+ aMyItem.get(position).addresses;
		Intent intent = new Intent(ListOfInfo.this, WebViews.class);
		intent.putExtra("url", url);
		startActivity(intent);

	}
}

class MyItem {
	Bitmap bits;
	String contents;
	String contents2;
	String addresses;

	MyItem(Bitmap bit, String content, String content2, String addresses) {
		bits = bit;
		this.contents = content;
		this.contents2 = content2;
		this.addresses = addresses;
	}
}

class MyListAdapter extends BaseAdapter {
	Context maincon;
	LayoutInflater Inflater;
	ArrayList<MyItem> aitem;
	int alayout;

	public MyListAdapter(Context context, int layout, ArrayList<MyItem> item) {
		maincon = context;
		Inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		alayout = layout;
		aitem = item;
	}

	public int getCount() {
		return aitem.size();
	}

	public String getItem(int position) {
		return aitem.get(position).contents;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		if (convertView == null) {
			convertView = Inflater.inflate(alayout, parent, false);
		}

		ImageView img = (ImageView) convertView.findViewById(R.id.dateRowImg);
		img.setImageBitmap(aitem.get(pos).bits);

		TextView tv = (TextView) convertView.findViewById(R.id.toptext);
		tv.setText(aitem.get(pos).contents);

		TextView tv1 = (TextView) convertView.findViewById(R.id.bottomtext);
		tv1.setText(aitem.get(pos).contents2);

		return convertView;
	}
}